package com.example.vue3.tess4j;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.example.vue3.model.ResultCode;
import com.example.vue3.model.ResultData;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * Java 使用 tess4j 识别图片上的文字
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2022/11/8 21:06
 */
@RestController
public class Tess4jController {

    private static final Logger LOG = LoggerFactory.getLogger(Tess4jController.class);

    /**
     * http://localhost:8080/tess4j/doOCR
     * 单文件上传 & Java 使用 tess4j 识别图片上的文字
     *
     * @param uploadFile：SpringMVC 文件上传封装对象，多文件上传时，使用 MultipartFile 列表(List)或者数组(Array)都可以
     */
    @RequestMapping("tess4j/doOCR")
    @ResponseBody
    public ResultData<Object> singleFileUpload(@RequestParam MultipartFile uploadFile) throws Exception {
        // String getOriginalFilename() : 包含文件名与格式，如:123.mp4
        // long getSize() ：返回文件的大小（字节）。如果为空，则为0
        // String getContentType() ：返回内容类型，如果未定义，则返回{@code null}（或在多部分表单中未选择任何文件）
        // String byteCountToDisplaySize(final long size)：返回文件大小的可读版本,如 20.77M
        String fileNameAndFormat = uploadFile.getOriginalFilename();
        if (StrUtil.isBlank(fileNameAndFormat)) {
            return new ResultData<>(ResultCode.FAIL.getCode(), "请先选择文件！", null);
        }
        Long fileSizeLong = uploadFile.getSize();
        String contentType = uploadFile.getContentType();
        String fileSizeStr = FileUtils.byteCountToDisplaySize(fileSizeLong);
        String format = fileNameAndFormat.substring(fileNameAndFormat.lastIndexOf("."));
        LOG.info("文件上传：fileNameAndFormat={}，fileSizeLong={}，contentType={}，fileSizeStr={}，format={}",
                fileNameAndFormat, fileSizeLong, contentType, fileSizeStr, format);
        List<String> formatList = ListUtil.toList(".gif,.jpg,.png,.jpeg".split(","));
        if (!formatList.contains(format.toLowerCase())) {
            return new ResultData<>(ResultCode.FAIL.getCode(), "仅支持格式：.gif,.jpg,.png,.jpeg,.bmp,.webp", null);
        }
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File tmpFile = new File(tmpDir, "doOCR_" + IdUtil.fastSimpleUUID() + format);
        uploadFile.transferTo(tmpFile);
        LOG.info("临时文件存储：{}", tmpFile.getAbsolutePath());

        String readImg2Text = Tess4jUtils.readImg2Text(tmpFile);
        LOG.info("图片识别文件结果：{}", readImg2Text);

        return new ResultData<>(readImg2Text);
    }


}
